# -*- coding: utf-8 -*-
# @Author   : zxc19
# @Time     : 2023/7/6 21:12
# @FileName : redis_util.py
# @Desc     : 请输入功能模块描述
import redis as redis
from loguru import logger

from libs.ssh_tunnel import SSHTunnelObj, SSHTunnel


class RedisUtil(object):
    def __init__(self, host: str, port: int = 6379, password: str = None, use_ssh: bool = False,
                 ssh_host: str = None,
                 ssh_port=22,
                 ssh_username: str = None, ssh_password: str = None):
        if use_ssh:
            self.ssh_tunnel_obj = SSHTunnelObj(
                ssh_host=ssh_host if ssh_host else host,
                ssh_port=ssh_port,
                ssh_username=ssh_username,
                ssh_password=ssh_password,
                remote_bind_host=host if ssh_host else '127.0.0.1',
                remote_bind_port=port
            )
            self._ssh_txy = SSHTunnel(self.ssh_tunnel_obj)
            logger.info(self._ssh_txy.server.is_alive)
            local_port = self._ssh_txy.server.local_bind_port  # 获取转发端口
            self.client = redis.Redis(host='127.0.0.1', port=local_port, password=password, decode_responses=True)
        else:
            self.client = redis.Redis(host=host, port=port, password=password, decode_responses=True)

    def keys(self, pattern='*') -> list:
        return self.client.keys(pattern=pattern)

    def get(self, name: str) -> str | None:
        return self.client.get(name=name).strip('"')

    def close(self):
        self.client.close()
        self._ssh_txy.close()

    def __del__(self):
        self.close()


if __name__ == '__main__':
    client = RedisUtil(
        host='10.121.110.40', use_ssh=True, ssh_port=22000, ssh_username='root', ssh_password='LSP@300768'
    )
    print(client.keys())
    client.close()
